package Library.Events;

import java.awt.event.*;
import java.util.*;

/**
 * Event dient als een Multicast Delegation met een ReturnValue
 * Op dit event kunnen dus meerdere handlers worden geregistreerd.
 * @param <T>
 * @param <R>
 */
public class EventEx<T extends ActionEvent, R>
{
    /**
     *
     */
    protected final List<ActionListenerEx<R, T>> m_EventHandlers = Collections.synchronizedList(new ArrayList<ActionListenerEx<R, T>>());
    /**
     *
     * @param listener
     */
    public void register(ActionListenerEx<R, T> listener)
    {
	synchronized (m_EventHandlers)
	{
	    m_EventHandlers.add(listener);
	}
    }
    
    /**
     *
     * @param e
     */
    public void trigger(T e)
    {
	synchronized (m_EventHandlers)
	{
	    Iterator<ActionListenerEx<R, T>> it = m_EventHandlers.iterator();
	    while (it.hasNext())
	    {
		try
		{
		    it.next().actionPerformed(e);
		}
		catch (Exception ex)
		{
		    // Don't through else it could generate a deadlock
		    ex.printStackTrace();
		}
	    }
	}
    }
    
    /**
     *
     * @param listener
     */
    public void unregister(ActionListenerEx<R, T> listener)
    {
	synchronized (m_EventHandlers)
	{
	    m_EventHandlers.add(listener);
	}
    }
    
    /**
     *
     */
    public void clear()
    {
	synchronized (m_EventHandlers)
	{
	    m_EventHandlers.clear();
	}
    }
}
